package redpacket.task;

import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redpacket.mapper.RedPacketMapper;
import redpacket.model.RedPacket;

import java.time.LocalDateTime;
import java.util.List;

@Component
@EnableScheduling
@RequiredArgsConstructor
public class ExpireTask {

    private static final Logger log = LoggerFactory.getLogger(ExpireTask.class);
    private final RedPacketMapper redPacketMapper;
    private final StringRedisTemplate redis;

    private String listKey(long packetId){ return "rp:%d:list".formatted(packetId); }

    @Scheduled(fixedDelay = 15000)
    public void scanExpired() {
        List<RedPacket> expired = redPacketMapper.findExpired(LocalDateTime.now());
        for (RedPacket rp : expired) {
            Long remain = redis.opsForList().size(listKey(rp.getId()));
            // In real system: refund remain amounts to sender
            log.info("Packet {} expired, remain items: {}", rp.getId(), remain);
            redPacketMapper.updateStatus(rp.getId(), 3);
            // Optional: cleanup Redis keys (list will auto-expire via TTL set on create)
        }
    }
}
